package cn.bytepath.base.controller;

import cn.bytepath.annotation.BaseUpload;
import cn.bytepath.util.FastDfsUtil;
import cn.bytepath.util.PageResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

/**
 * 所有controller层的超类
 * @author Jack.C
 * @createDate 2022-02-10
 * @version 1.0
 */
public class BaseController {

    /**
     * 上传文件到fastdfs中
     * @param file 需上传的文件对象
     * @return: cn.bytepath.util.PageResult
     * @update 2022/2/10
     */
    public PageResult upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extname = originalFilename.split("\\.")[originalFilename.split("\\.").length - 1];
            byte[] bytes = file.getBytes();
            String path = FastDfsUtil.upload(bytes, extname);
            return PageResult.SUCCESS.setData(path);
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }

    }

    public PageResult deleteFile(String fileName) {
        try {
            String[] split = fileName.split("=");
            String group = split[0];
            String path = split[1].replaceAll(":", "/");
            FastDfsUtil.delete(group, path);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }
}
